package com.billdowney.qq.robot.plugins.provide;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.billdowney.qq.robot.plugins.RobotPlugin;
import com.billdowney.qq.robot.plugins.RobotPluginContent;
import com.billdowney.qq.robot.plugins.RobotPluginInfo;
import com.billdowney.qq.robot.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.message.data.PlainText;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * AI机器人插件
 *
 * @author BillDowney
 * @date 2021/4/8 11:11
 */
@Component
@Slf4j
public class AiRobotPlugin implements RobotPlugin {

    @Override
    public RobotPluginInfo info() {
        return RobotPluginInfo.create("AI机器人插件", true, Integer.MAX_VALUE)
                .addDescLn("接入别的AI机器人，默认最后执行，前面没有回复消息的时候才执行");
    }

    @Override
    public void execute(RobotPluginContent content) {
        // 消息为空、好友消息、群里被@
        if (content.getReplyMessages().isEmpty() && content.getRobotEventEnum().isMessageEvent()) {
            Bot bot = content.getMessageEvent().getBot();
            // 记录机器人是否被艾特
            AtomicBoolean flag = new AtomicBoolean(false);
            // 接收的字符串消息
            StringBuilder strMsg = new StringBuilder();
            content.getMessageEvent().getMessage().forEach(singleMessage -> {
                // 过滤艾特消息
                if (singleMessage instanceof At) {
                    if (((At) singleMessage).getTarget() == bot.getId()) {
                        flag.set(true);
                    }
                } else {
                    strMsg.append(singleMessage.contentToString().trim());
                }
            });
            // 如果是群消息，则需要被@才回复消息
            if (content.getRobotEventEnum().isGroupMsg() && flag.get()) {
                MessageChainBuilder builder = MessageUtil.createBuilder();
                builder.append(new At(content.getMessageEvent().getSender().getId()));
                if (strMsg.length() == 0) {
                    builder.append(new PlainText(" 艾特我不说话，是想干嘛"));
                } else {
                    builder.append(new PlainText(" " + this.qingYunKe(strMsg.toString())));
                }
                content.putReplyMessage(builder.build());
            } else if (content.getRobotEventEnum().isFriendMsg()) {
                if (strMsg.length() == 0) {
                    content.putReplyMessage("艾特我不说话，是想干嘛");
                } else {
                    content.putReplyMessage(this.qingYunKe(strMsg.toString()));
                }
            }
        }
    }

    /**
     * https://api.qingyunke.com/
     * 青云客ai机器人
     */
    public String qingYunKe(String msg) {
        String url = "https://api.qingyunke.com/api.php";
        try {
            HttpResponse httpResponse = HttpRequest.get(url)
                    // 必需，固定值
                    .form("key", "free")
                    // 可选，0表示智能识别
                    .form("appid", "0")
                    // 必需，关键词，提交前请先经过 urlencode 处理
                    .form("msg", URLEncoder.encode(msg, "UTF-8"))
                    .execute();
            return JSONUtil.parseObj(httpResponse.body()).getStr("content").replaceAll("\\{br}", "\n");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        }
    }
}
